//
// Created by sxt on 2023/10/18.
//
#include <iostream>
#include <WorkExecutor.h>
#include <fstream>
#include <TypeDescriptor.h>

using namespace myreflect;

std::vector<std::string> readTaskConfig() {
    std::vector<std::string> tasks;
    std::string configPath = std::string(CMAKE_SOURCE_DIR) + "/test/config/task.config";
    std::ifstream file(configPath);

    if (file.is_open()) {
        std::string line;
        while (getline(file, line)) {
            tasks.push_back(line);
        }
        file.close();
    } else {
        std::cerr << "Unable to open task.config file!" << std::endl;
    }

    return tasks;
}

void initRelect() {
    WorkExecutor::makeReflectable();
}

int main() {
    // 初始化反射
    initRelect();
    // 读取任务配置
    auto tasks = readTaskConfig();
    // 任务链构建
    WorkExecutor *workExecutor{nullptr}, *head{nullptr};
    for (const auto& task : tasks) {
        // task 格式：taskName###taskType
        auto index = task.find("###");
        // split ###
        auto taskName = task.substr(0, index);
        auto taskType = task.substr(index + 3);

        TypeDescriptor &typeDescriptor = getClassByName("WorkExecutor");
        if (workExecutor == nullptr) {
            workExecutor = static_cast<WorkExecutor *>(typeDescriptor.newInstance());
            typeDescriptor.getField("taskName").setValue(*workExecutor, taskName);
            typeDescriptor.getField("taskType").setValue(*workExecutor, taskType);
            head = workExecutor;
        } else {
            auto tmpWorkExecutor = static_cast<WorkExecutor *>(typeDescriptor.newInstance());
            typeDescriptor.getField("taskName").setValue(*tmpWorkExecutor, taskName);
            typeDescriptor.getField("taskType").setValue(*tmpWorkExecutor, taskType);
            typeDescriptor.getMethod("addNext").invoke(*head, tmpWorkExecutor);
            head = tmpWorkExecutor;
        }
    }
    // 任务执行
    workExecutor->execute();
    return 0;
}
